package com.youxin.authserver.service.serviceimpl;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.youxin.authserver.service.LoginService;
import com.youxin.busfoundation.MessageUtils;
import com.youxin.busfoundation.bean.BusinessMessages;
import com.youxin.busfoundation.bean.ResponseObject;
import com.youxin.busfoundation.bean.login.PayloadBean;
import com.youxin.busfoundation.bean.login.RequestLoginBean;
import com.youxin.busfoundation.bean.login.RequestRefreshToken;
import com.youxin.busfoundation.bean.login.UserInfo;
import com.youxin.busfoundation.common.BusinessDataException;
import com.youxin.busfoundation.common.GlobalConfig;
import com.youxin.busfoundation.common.LoginAuth;
import com.youxin.busfoundation.common.VerifyCodeUtils;
import com.youxin.busfoundation.common.login.Jwt;
import com.youxin.busfoundation.common.redis.RedisOperator;
import com.youxin.busfoundation.enums.LoginType;
import com.youxin.busfoundation.enums.SystemType;
import com.youxin.busfoundation.sms.SmsUtils;
import com.youxin.cpcenter.dao.TbEntMemberInfoMapper;
import com.youxin.cpcenter.dao.TbMemberInfoMapper;
import com.youxin.cpcenter.model.TbEntMemberInfo;
import com.youxin.cpcenter.model.TbMemberInfo;
import com.youxin.cpcenter.utils.LoginUtils;
import com.youxin.foundation.db.redis.RedisClusterCommand;
import com.youxin.foundation.utils.JsonUtils;
import com.youxin.foundation.utils.StringUtils;


@Service("loginService")
public class LoginServiceImpl  implements LoginService {
	protected static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(LoginServiceImpl.class);
	
	@Autowired
	private TbMemberInfoMapper tbMemberInfoMapper;
	@Autowired 
	private TbEntMemberInfoMapper tbEntMemberInfoMapper;
	/**
	 * 登录功能
	 */
	@Override
	public ResponseObject login(RequestLoginBean bean) {
		if (bean.getExtra().getAppid()==SystemType.CP.getValue()) {
			PayloadBean payloadBean=bean.getExtra();
			if(bean.getExtra().getLogintype()==LoginType.MobileCode.getValue())
			{
				String code=RedisOperator.getLoginVerifyCode(bean.getMobile());
				if(StringUtils.isNullOrEmpty(code))
				{
					return ResponseObject.userFailure("验证码错误");
				}
				
				if(code.equals(bean.getCode()))
				{
					UserInfo userInfo=LoginUtils.loginWithMobile(tbMemberInfoMapper, tbEntMemberInfoMapper, bean.getMobile());
					if(userInfo==null)
					{
						return ResponseObject.userFailure("登陆失败");
					}
					/**
					 * 登陆认证Token
					 */
					payloadBean.setUserid(userInfo.getId());
					payloadBean.setCreateTime(System.currentTimeMillis());
					payloadBean.setExpires(GlobalConfig.DEFAULT_EXPIRES_MILLISECOND);
					
					Map<String, Object> payloadMap=JsonUtils.objectToMapObject(payloadBean);
					String token=Jwt.createToken(payloadMap);
					
					if(StringUtils.isNullOrEmpty(token))
					{
						return ResponseObject.userFailure("生成登录标识错误");
					}			
					userInfo.setToken(token);
					RedisOperator.removeLoginVerifyCode(bean.getMobile());
					return ResponseObject.successObject(userInfo);
				}else{
					return ResponseObject.userFailure("验证码错误");
				}
			}else{
				return ResponseObject.userFailure("不支持的登录类型");
			}
		}else{
			return ResponseObject.userFailure("不支持的Appid");
		}		
	}
	
	
	
	@Override
	public ResponseObject refreshToken(RequestRefreshToken bean) {
		PayloadBean payloadBean=Jwt.validToken(bean.getToken());
		if(payloadBean==null){
			return new ResponseObject(BusinessMessages.LOGIN_INFO);
		}		
		payloadBean.setCreateTime(System.currentTimeMillis());
		payloadBean.setExpires(GlobalConfig.DEFAULT_REFRESH_MILLISECOND);
		Map<String, Object> payloadMap=JsonUtils.objectToMapObject(payloadBean);
		String token=Jwt.createToken(payloadMap);		
		return ResponseObject.successObject(token);
	}
	
	@Override
	public ResponseObject requestLoginVerifyCode(com.youxin.busfoundation.bean.login.RequestLoginVerifyCode bean) throws Exception {
		String code = VerifyCodeUtils.getVerifyCode();
		bean.setCode(code);
		String message = MessageUtils.verifyCode(code);		
		String result=RedisOperator.saveLoginVerifyCode(bean);
		ResponseObject object = SmsUtils.send(bean.getMobile(), message);
		return object;
	}

	@Override
	public ResponseObject logout(RequestRefreshToken bean,HttpServletRequest request) {
		PayloadBean payloadBean=Jwt.validToken(bean.getToken());
		if(payloadBean==null)
		{
			throw new BusinessDataException("用户未登录");
		}		
		Long result=RedisOperator.removeUserInfo(payloadBean.getUserid());
		if(result!=null&&result.longValue()==1){
			return ResponseObject.successObject();
		}
		if(result!=null&&result.longValue()==-1){
			return ResponseObject.userFailure("用户未退出登录");
		}
		return ResponseObject.userFailure("退出登录失败,系统错误");
	}

}
